package com.example.demo.controller;

import com.example.demo.model.ApiResponse;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public ResponseEntity<ApiResponse<List<User>>> getUsersByRole(@RequestParam(required = false) String role) {
        List<User> users;
        if (role != null) {
            users = userRepository.findByRole(User.Role.valueOf(role.toUpperCase()));
        } else {
            users = userRepository.findAll();
        }
        return ResponseEntity.ok(ApiResponse.success(users));
    }
    @PutMapping("/{userId}")
    public ResponseEntity<ApiResponse<User>> updateUser(
            @PathVariable Integer userId,
            @RequestBody User updatedUser) {

        // 检查用户是否存在
        User existingUser = userRepository.findById(userId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在"));

        // 更新允许修改的字段（保护不可修改字段）
        if(updatedUser.getUsername() != null && !updatedUser.getUsername().isEmpty()) {
            // 检查用户名是否已存在（排除自己）
            if(userRepository.existsByUsernameAndUserIdNot(updatedUser.getUsername(), userId)) {
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "用户名已被使用");
            }
            existingUser.setUsername(updatedUser.getUsername());
        }
// 添加avatar更新逻辑
        if(updatedUser.getAvatar() != null && !updatedUser.getAvatar().isEmpty()) {
            existingUser.setAvatar(updatedUser.getAvatar());
        }
        if(updatedUser.getPassword() != null && !updatedUser.getPassword().isEmpty()) {
            existingUser.setPassword(updatedUser.getPassword());
        }

        if(updatedUser.getRole() != null) {
            existingUser.setRole(updatedUser.getRole());
        }

        // 保存更新
        User savedUser = userRepository.save(existingUser);
        return ResponseEntity.ok(ApiResponse.success(savedUser));
    }

}